﻿
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;

namespace Tau.Common.Utilities
{
    public class EmailAttachment
    {
        public string AttachmentName {get;set;}
        public byte[] Attachment{get;set;}
    }

    public static class EmailUtilities
    {
        /// <summary>
        /// Send email, using values from config for SMTP server and login
        /// </summary>
        /// <param name="messageBody"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        public static void SendEmail(string messageBody, string from, string to, string subject)
        {
            SendEmail(messageBody, from, to, subject, null);
        } 

        /// <summary>
        /// Sends email, using values from config for SMTP server and login, with attachments
        /// </summary>
        /// <param name="messageBody"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="subject"></param>
        /// <param name="attachments"></param>
        public static void SendEmail(string messageBody, string from, string to, string subject, List<EmailAttachment> attachments)
        {
            var message = new MailMessage
            {
                From = new MailAddress(from),
                Subject = subject,
                Body = messageBody,
                IsBodyHtml = false
            };
            message.To.Add(to);

            if (attachments != null && attachments.Count > 0)
            {
                foreach(var attachment in attachments)
                {
                    //Set attachment name and content stream
                    var stream = new MemoryStream();
                    stream.Write(attachment.Attachment, 0, attachment.Attachment.Length);
                    var mailAttachment = new Attachment(stream, attachment.AttachmentName);

                    //Add attachment
                    message.Attachments.Add(mailAttachment);
                }
                
            }

            var smtp = new SmtpClient
            {
                Host = ConfigurationManager.AppSettings["SMTPServer"],
                EnableSsl = false,
                Credentials = new NetworkCredential(ConfigurationManager.AppSettings["SMTPUsername"], ConfigurationManager.AppSettings["SMTPPassword"])
            };

            smtp.Send(message);
        }
    }
}
